﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;

namespace CodeStash.Mef
{
    [Export(typeof(IControllerFactory))]
    public class MefControllerFactory : DefaultControllerFactory
    {
        [ImportMany]
        public IEnumerable<ExportFactory<IController, IControllerMeta>> Controllers { get; set; }

  

        public override IController CreateController(RequestContext requestContext, string controllerName)
        {
            try
            {
                // finds the ExportFactory instance that matches the controller name
                var factory = Controllers.
                    Where(fac => fac.Metadata.ControllerName.Equals(controllerName, StringComparison.OrdinalIgnoreCase)).
                    FirstOrDefault();

                if (factory == null)
                {
                    throw new HttpException(404, "Not found for " + controllerName);
                }

                var lifeTimeContext = factory.CreateExport();

                // saves lifetime object for later disposal
                requestContext.HttpContext.Items["controller.lifetime.context"] = lifeTimeContext;

                return lifeTimeContext.Value;
            }
            catch
            {
                return base.CreateController(requestContext, controllerName);
            }
        }

        public override void ReleaseController(IController controller)
        {
            // retrives the lifetime object for disposal
            var context = (ExportLifetimeContext<IController>)
                HttpContext.Current.Items["controller.lifetime.context"];

            if (context != null)
            {
                context.Dispose();
            }
        }

        public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
        {
            return SessionStateBehavior.Default;
        }
    }
}